import request, { enhancedFetch } from './config'

// 获取用户会话列表

export function login(username, password) {
  const params = new URLSearchParams()
  params.append('grant_type', 'password')
  params.append('username', username)
  params.append('password', password)
  params.append('scope', '')
  params.append('client_id', 'string')
  params.append('client_secret', 'string')

  return request({
    url: '/dk/auth/jwt/login',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    data: params,
  })
}
export function phoneLogin(phone, code) {
  return request({
    url: '/dk/auth/sms-login',
    method: 'post',
    data: {
      phone,
      code,
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  })
}

export function sendSmsCode(phone) {
  return request({
    url: '/dk/auth/send-sms-code',
    method: 'post',
    data: {
      phone,
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  })
}

export function get_user_sessions() {
  return request({
    url: '/dk/sessions/get_user_sessions',
    method: 'get',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
  })
}

export function uploadFile(formData) {
  return request({
    url: '/dk/sessions/upload_file',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
}

// 创建会话
export function createSession(datasetId = null, sessionTitle = '') {
  const formData = new FormData()
  
  // 只有当datasetId不为null时才添加dataset_id参数
  if (datasetId !== null && datasetId !== undefined) {
    formData.append('dataset_id', datasetId)
  }
  
  if (sessionTitle) {
    formData.append('session_title', sessionTitle)
  }

  return request({
    url: '/dk/sessions/create_session',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
}

export function startAnalysis(dataset_id) {
  return request({
    url: '/dk/sessions/start_analysis',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { dataset_id },
  })
}

export function getAnalysisStatus(fileId) {
  return request({
    url: '/dk/sessions/analysis_status',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { sessionid: fileId },
  })
}

export function getSessionDetails(session_id) {
  return request({
    url: '/dk/sessions/get_session_details',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { session_id },
  })
}

export function sendMsg(session_id, message) {
  return request({
    url: '/dk/sessions/send_msg',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { message, session_id },
  })
}

export function getMsg(session_id, message_id) {
  return request({
    url: '/dk/sessions/get_msg',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { message_id, session_id },
  })
}

export function deleteMsg(message_id) {
  return request({
    url: '/dk/sessions/delete_message',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { message_id },
  })
}

export function deleteSession(sessionid) {
  return request({
    url: '/dk/sessions/delete_session',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { sessionid },
  })
}

export async function generateReport(report_type, session_id) {
  return enhancedFetch('/dk/sessions/generate_report', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'text/event-stream',
      'Cache-Control': 'no-cache',
      Connection: 'keep-alive',
    },
    body: new URLSearchParams({ report_type, session_id }),
  })
}
export async function getMsgFx(message_id, umessage_id) {
  return enhancedFetch('/dk/sessions/get_msg_fx', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'text/event-stream',
      'Cache-Control': 'no-cache',
      Connection: 'keep-alive',
    },
    body: new URLSearchParams({ message_id, umessage_id }),
  })
}

// 与智能助手对话，流式输出
export async function chatWithAssistant(
  message,
  session_id = '',
  session_title = '智能助手对话',
  generate_friendly_reply = true
) {
  const params = new URLSearchParams()
  params.append('message', message)
  if (session_id) {
    params.append('session_id', session_id)
  }
  params.append('session_title', session_title)
  params.append('generate_friendly_reply', generate_friendly_reply)

  return enhancedFetch('/dk/sessions/chat_with_assistant', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'text/event-stream',
      'Cache-Control': 'no-cache',
      Connection: 'keep-alive',
    },
    body: params,
  })
}

export function getUdbSessionData(session_id, page, page_size) {
  return request({
    url: '/dk/sessions/get_udb_sessionid_data',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: {
      sessionid: session_id,
      page,
      page_size,
    },
  })
}

// 锁定/解锁分析维度
export function toggleDimensionlock(dimension_id) {
  return request({
    url: '/dk/sessions/toggle_dimension_lock',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { dimension_id },
  })
}

export function generateDimensionCharts(message_id) {
  return request({
    url: '/dk/sessions/generate_dimension_charts',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { message_id },
  })
}

// 提交图表修改建议
export function submitChartSuggestion(messageId, tableIndex, suggestion) {
  return request({
    url: '/dk/sessions/update_chart_config',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: {
      message_id: messageId,
      table_index: tableIndex,
      suggestion,
    },
  })
}

export function addReport(report_title, description, dataset_id, filters = []) {
  const data = {
    report_title,
    description,
    dataset_id,
  }

  // 如果有筛选条件，将其添加到请求中
  if (filters && filters.length > 0) {
    data.filters = JSON.stringify(filters)
  }

  return request({
    url: '/dk/sessions/add_report',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data,
  })
}

// 生成分析大纲
export function generateAnalysisOutline(report_id) {
  return request({
    url: '/dk/sessions/generate_analysis_outline',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: {
      report_id,
    },
  })
}

// 生成分析维度内容
export function generateDimensionContent(dimension_id, user_opinion = '') {
  return request({
    url: '/dk/sessions/generate_dimension_fx',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { dimension_id, user_opinion },
  })
}

// 获取分析维度详情
export function getAnalysisDimension(dimension_id) {
  return request({
    url: '/dk/sessions/get_analysis_dimension',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { dimension_id },
  })
}

// 获取会话关联的所有报告
export function getMyReports() {
  return request({
    url: '/dk/sessions/get_my_reports',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: {},
  })
}

// 获取报告详情及章节信息
export function getReportDetails(report_id) {
  return request({
    url: '/dk/sessions/get_report_details',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { report_id },
  })
}

// 删除报告及其章节
export function deleteReport(report_id) {
  return request({
    url: '/dk/sessions/delete_report',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { report_id },
  })
}

export function deleteDimension(dimension_id) {
  return request({
    url: '/dk/sessions/delete_analysis_dimension',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { dimension_id },
  })
}

export function deleteMyDataset(dataset_id) {
  return request({
    url: '/dk/sessions/delete_my_dataset',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { dataset_id },
  })
}

export function getDatasetInfo(dataset_id) {
  return request({
    url: '/dk/sessions/dataset-info',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { dataset_id },
  })
}

export function updateAnalysisResult(dimension_id, analysis_result) {
  return request({
    url: '/dk/sessions/update_analysis_result',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { dimension_id, analysis_result },
  })
}

export function updateReportInfo(
  report_id,
  report_title = '',
  report_description = '',
  data_filters = '',
) {
  return request({
    url: '/dk/sessions/update_report_info',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { report_id, report_title, report_description, data_filters },
  })
}

// 任务拆解
export function taskBreakdown(user_requirement, message_id) {
  return request({
    url: '/dk/sessions/task_breakdown',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { user_requirement, message_id },
  })
}

export function getTasksStatus(message_id) {
  return request({
    url: '/dk/sessions/get_tasks_status',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { message_id },
  })
}

// 获取会话消息列表（分页）
export function getSessionMessages(session_id, page = 1, page_size = 2) {
  return request({
    url: '/dk/sessions/get_session_messages',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { session_id, page, page_size },
  })
}

// 获取临时会话
export function getTempSession(dataset_id = '') {
  return request({
    url: '/dk/sessions/get_temp_session',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { dataset_id },
  })
}

export function updateSessionDatasets(session_id, dataset_ids) {
  return request({
    url: '/dk/sessions/update_session_datasets',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { session_id, dataset_ids },
  })
}

// 更新报告的数据筛选条件

/**
 * 根据消息ID获取关联任务的数据
 * @param {string} messageId - 消息ID
 * @returns {Promise<Object>} 任务数据响应
 */
export const getMessageTaskData = async (messageId) => {
  try {
    const formData = new FormData()
    formData.append('message_id', messageId)

    const response = await request({
      url: '/dk/sessions/get_message_task_data',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    return response
  } catch (error) {
    console.error('获取消息任务数据失败:', error)
    throw error
  }
}
